import React, { useEffect, useState, useImperativeHandle } from 'react';
import ConditionItem from './ConditionItem';
import { randomKey } from '../../utils/utils';
import { Message } from 'antd';
import { validateConditions } from './validate';
import { cloneDeep } from 'lodash';
import './conditions.less';

export default function Conditions(props) {
  const { logs } = props;
  const [value, setValue] = useState([]);
  const [singleJunction, setSingleJunction] = useState(props.singleJunction); // 单个关系
  useImperativeHandle(props.createRef, () => ({
    // 暴露方法给父组件,收集验证值
    getValue: (isNeedLeft, cb) => {
      const finallyValue = cloneDeep(value);
      if (singleJunction && finallyValue && finallyValue[0]) finallyValue[0].junction_type = 'none';
      const isValidate = validateNow(finallyValue, isNeedLeft); // 验证数据
      if (isValidate) {
        cb(finallyValue, null);
      } else {
        cb(finallyValue, true);
      }
    },
  }));

  useEffect(() => {
    const newValue = cloneDeep(props.value);
    if (singleJunction && newValue && newValue.length > 0) newValue[0].junction_type = singleJunction;
    props.value && props.value.length > 0
      ? setValue(newValue)
      : setValue([
          {
            id: randomKey(),
            junction_type: singleJunction || 'none',
          },
        ]);
  }, [props.value]);

  // 验证数据
  function validateNow(value, isNeedLeft) {
    try {
      validateConditions(value, isNeedLeft);
      return value;
    } catch (error) {
      console.log(error);
      Message.warning(error);
      return false;
    }
  }

  const handleChange = (id, val) => {
    if (singleJunction) setSingleJunction(val.junction_type);
    value.forEach((item) => {
      if (item.id === id) {
        item = val;
      } else {
        if (singleJunction) item.junction_type = val.junction_type;
      }
    });
    setValue(cloneDeep(value));
    props.onChange && props.onChange(cloneDeep(value));
  };

  const add = (index) => {
    value.splice(index + 1, 0, {
      id: randomKey(),
      junction_type: singleJunction || 'and',
    });
    setValue(cloneDeep(value));
    props.onChange && props.onChange(cloneDeep(value));
  };
  const del = (index) => {
    value.splice(index, 1);
    if (value.length === 1) {
      value[0].junction_type = singleJunction || 'none';
    }
    setValue(cloneDeep(value));
    props.onChange && props.onChange(cloneDeep(value));
  };

  return (
    <div className='conditions'>
      {value.map((item, index) => {
        const _isHit = ((logs && logs.rules && logs.rules.find((it) => it.id === item.id)) || {}).hit;
        return (
          <ConditionItem
            {...props}
            value={item}
            key={item.id}
            placeholder={props.placeholder}
            variable={props.variable}
            using_variables={props.using_variables}
            onChange={handleChange.bind(this, item.id)}
            onAdd={add.bind(this, index)}
            onDel={del.bind(this, index)}
            isAddBtn={index === value.length - 1}
            isDelBtn={value.length !== 1}
            operatorOptions={props.operatorOptions}
            disabled={props.disabled}
            compareData={(props.compareData && props.compareData[index]) || undefined}
            leftDisable={props.leftDisable || false}
            isSingleCondition={props.isSingleCondition}
            isHit={_isHit}
            singleJunction={singleJunction}
            itemIndex={index}
          />
        );
      })}
    </div>
  );
}
